import { getMenu } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getIsAdmin } from '@/utils/auth'
// import pinyin from 'pinyin'
import App from '../../App.vue'
const state = {
  routeList: '',
  currentMenuList: JSON.parse(sessionStorage.getItem('currentMenuData'))?.menuList || [] // 点击模块得到的子菜单
}
const mutations = {
  SET_ROUTES: (state, routes) => {
    const plantform = getIsAdmin()
    if (plantform || process.env.NODE_ENV === 'development') { //
      state.routeList = constantRoutes.concat(routes)
    } else {
      constantRoutes.forEach(item => {
        if (item.meta?.role) {
          item.hidden = true
        }
      })
      state.routeList = constantRoutes
        .slice(0, constantRoutes.length - 1)
        .concat(routes)
    }
    router.addRoutes(routes)
  },
  //  清除路由
  CLEAR_ROUTES: (state) => {
    state.routeList = ''
    sessionStorage.removeItem('FIVE_MENU_LIST')
  },
  /**
   * @description: 设置点击顶部模块菜单得到的子菜单
   * @return {*}
   */
  SET_CURRENT_MENU_LIST: (state, currentMenuList) => {
    state.currentMenuList = currentMenuList
  }
}
const actions = {
  // 生成路由
  GenerateRoutes({ commit }, view) {
    if (!state.routeList || view) {
      return new Promise((resolve) => {
        // 向后端请求路由数据
        const menuData = JSON.parse(
          sessionStorage.getItem('FIVE_MENU_LIST')

        )
        if (Array.isArray(menuData) && menuData.length > 0 && !view) {
          resetRouter()
          const accessedRoutes = filterAsyncRouter(menuData)
          accessedRoutes.push({
            path: '*',
            redirect: '/404',
            hidden: true,
            meta: {
              roles: ['admin', 'editor']
            }
          })
          commit('SET_ROUTES', accessedRoutes)
          resolve(menuData)
        } else {
          getMenu().then((res) => {
            sessionStorage.setItem(
              'FIVE_MENU_LIST',
              JSON.stringify(res.data.data)
            )
            resetRouter()
            const accessedRoutes = filterAsyncRouter(res.data.data)
            accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
            commit('SET_ROUTES', accessedRoutes)
            resolve(res.data.data)
          })
        }
      })
    }
  },
  clearRoutes({ commit }) {
    commit('CLEAR_ROUTES')
  },
  setCurrentMenuList({ commit }, view) {
    commit('SET_CURRENT_MENU_LIST', view)
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter((route) => {
    const { name, icon, id } = route
    route.meta = {
      title: name,
      icon, id
    }
    // if (route.meta.title) {
    //   route.meta.pTitle = pinyin(route.meta.title, {
    //     style: pinyin.STYLE_NORMAL
    //   })
    //     .toString()
    //     .replace(/,/g, '')
    // }
    /**
     *  @param => type 菜单类型  1: 功能模块 2:菜单
     *  严格遵守  1 > 2 层级嵌套规则   严禁出现 菜单嵌套功能模块问题
     *
     */
    if(route.isLink === 1){
        route.component = App
        route.target = '_blank'
    }
    if (route.embedMode === 2) delete route.component // 如果 是外链 菜单 那么 删除 component
    if (route.componentPath && route.componentPath.length) {
      // console.log(route)
      // Layout组件特殊处理
      if (route.componentPath === 'Layout') {
        // route.component = Layout
        route.component = (resolve) => require([`@/layout`], resolve)
      } else if (route.componentPath === 'App') {
        console.log('vv')
        // route.component = App
        // route.target = '_blank'
      } else if (route.componentPath) {
        if (['home', 'dashboard'].includes(route.name)) {
          route.meta.affix = true
        }
        route.component = loadView(route.componentPath)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    // 只加载状态为展示1 的路由
    return route.status === 1
  })
}

export const loadView = (view) => {
  // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
